#!/bin/bash

# Script to call SGT "make_lib"

# Default values
Compiler=$WMCOMPILER
Memory=$WMMEMORY
export WM_DEBUG_PP_OPTIONS=__DEBUG_APP__

# Read available memory sizes
memsizes=$(cat $WMATHOME/TgtGen/WmGen/memsizes)

# Check parameters
ParamList=$@
for i in $ParamList
do
    case $i in

        # Help mode
        -h ) helpmode=on ;;

        # Rebuild All mode
        -c ) cleanmode=on
             subCleanOpt="-c" ;;

        # Forget -d option : always done
        -d ) echo "" ;;

        # No dependencies
        -n ) nodep=on ;;

        # Do not verify SDK version
        -v ) noVersionCheck=on
             subNoVersionCheckOpt="-v" ;;

        # All_clean option : just clean...
        all_clean ) cleanmode=on
                    justclean=on
                    subCleanOpt="all_clean" ;;

        # Arm Compiler
        -arm ) Compiler=arm ;;
        # Gcc Compiler
        -gcc ) Compiler=gcc ;;

        # Debug options
        -debug )        echo -n "" ;;
        -fulldebug )    export WM_DEBUG_PP_OPTIONS="__DEBUG_APP__ __DEBUG_FULL__"
                        subDebugOpt="-fulldebug" ;;
        -release )      unset WM_DEBUG_PP_OPTIONS
                        subDebugOpt="-release" ;;
        
        # Memory option
        -* )    # Browse for known memory sizes
                MemOpt=no
                for memsize in ${memsizes}
                do
                    if [ $i == "-${memsize}" ]
                    then
                        Memory=${memsize}
                        MemOpt=yes
                    fi
                done
                
                # Check for unknown option
                if [ $MemOpt == no ]
                then
                    # make_lib additional option
                    MakeLibOpt="$MakeLibOpt $i"
                fi ;;
        
        # Not a wmmake option
        * )     # Check if makefile name has already been set
                if [ -z "$makname" ]
                then
                    # Get makefile name
                    makname=$i
                    makroot=${makname%.[ms]*}
                else
                    # Use it as a make_lib option
                    MakeLibOpt="$MakeLibOpt $i"
                fi ;;

    esac
done

# Help mode
if [ "$helpmode" == on ] || [ "$makname" == -h ]
then
    cat $WMATHOME/TgtGen/WmGen/wmmake.hlp
    exit
fi

# Check environment...
echo Check environment settings...
if [ -z "$WMCOMPILER" ] || [ -z "$WMMEMORY" ] || [ -z "$WMCORESW" ] || [ -z "$(which make_lib 2> /dev/null)" ]
then
    # Environment is not correctly installed
    echo
    echo The Open AT environment is not correctly installed.
    echo Please run the \$WMATHOME/TgtGen/WmGen/wmcheck script and refer to the Tools Manual.
    exit 1
fi

# Check for non-provided project name
if [ -z "${makroot}" ]
then
    # First check for existing .scs file
    ScsList=$(ls *.scs 2> /dev/null)
    if [ ! -z "$ScsList" ]
    then
        makroot=$(echo $ScsList | sed -e "s/\([^ ]*\)\.scs[ ]*.*/\1/")
    fi
fi

# Check SCS file presence
if [ ! -f ${makroot}.scs ]
then
    echo
    echo Unable to find ${makroot}.scs project file.
    exit 1
fi

# Check SDK version wgt the project one, if required
if [ "$noVersionCheck" != on ]
then
    # Retrieve versions
    SDKVersion=$(cat $WMATHOME/TgtGen/version 2> /dev/null)
    PRJVersion=$(wmdisp ${makroot}.scs '//Project/@SDKVersion')
    
    # Remove spaces
    SDKVersion=${SDKVersion%%[ ]*}
    PRJVersion=${PRJVersion%%[ ]*}
    
    # Compare versions
    if [ "$PRJVersion" != "$SDKVersion" ]
    then
        # Versions do not match
        
        # Compute empty versions
        if [ -z "$PRJVersion" ] ; then PRJVersion="a previous" ; fi
        if [ -z "$SDKVersion" ] ; then SDKVersion="an unknown" ; fi
        
        # Check running OS
        if [ -z "$(which cygcheck 2> /dev/null)" ]
        then
            # Running under Linux: text prompt
            PromptMsg="You are currently using $SDKVersion SDK version.
This project has been built with $PRJVersion version.
You should use the Open AT Wizard to update this project settings.
Do you want to continue building this project anyway (y/n) ? "
            
            echo -n "$PromptMsg"
            read UserInput
        else
            # Running under Cygwin: MessageBox
            PromptMsg="Open AT Settings mismatch/You are currently using $SDKVersion SDK version./This project has been built with $PRJVersion version./You should use the Open AT Wizard to update this project settings./Do you want to continue building this project anyway "
            
            $WMATHOME/TgtGen/WmGen/WmDispSettings.exe -q ${PromptMsg} '?'
            if [ $? == 1 ]
            then
                # User clicked Yes
                UserInput=y
            fi
        fi
        
        # Check User input
        if [ "$UserInput" != y ] && [ "$UserInput" != y ]
        then
            # Give up
            echo Process aborded by the user.
            exit 1
        else
            # Do not ask the question for sub-processes
            subNoVersionCheckOpt="-v"
        fi
    fi
fi

# Synchronize Makefiles
wmsync ${makroot}
Ret=$?
if [ $Ret -ne 0 ]
then
    echo
    echo Makefile synchronization error...
    exit 1
fi

if [ "$nodep" != on ]
then
    # Browse for libraries dependencies
    for LibPath in $(wmdisp ${makroot}.mak PATH_ROOT_LIB)
    do
        # Update relative library path
        if [ "${LibPath:0:1}" == "." ]
        then
            LibPath=$Compiler/mak/$LibPath
        fi
        
        # Browse Library names
        for LibName in $(wmdisp ${makroot}.mak PREFIXED_LIB_LIST)
        do
            # Check if project exist
            if [ -f $LibPath/$LibName.scs ]
            then
                # Update library project
                cd $LibPath
                wmmake $LibName -$Compiler ${subCleanOpt} ${subDebugOpt} ${subNoVersionCheckOpt}
                if [ $? == 1 ]
                then
                    # Sub-process error
                    exit 1
                fi
                cd -
            fi
        done
    done
fi

# Add compiler and memory options

# Try for binary
if [ -f ${Compiler}/mak/${Compiler}_${makroot}_${Memory}.mak ]
then
    # Binary mode
    makname="${Compiler}_${makroot}_${Memory}"
else
    # Library mode
    makname="${Compiler}_${makroot}"
fi

# Go to compiler directory
if [ ! -z "$Compiler" ]
then
    cd $Compiler
fi

# On clean mode : clean before
if [ "$cleanmode" == on ]
then
    make_lib ${makname} all_clean
fi

# Test for Just Clean option
if [ "$justclean" == on ]
then
    exit 0;
fi

# just call make_lib
make_lib ${makname} -bin -dwl -ne2p -d

# for binary files
if [ -f out/${makname}.wpb ]
then
    # Get ROBASE address
    ROBASE=$(wmdisp $WMATHOME/TgtGen/WmGen/mak/memory_${Memory}.mak ROBASE)
    
    # Build compressed binary dwl
    create_bin -fdwl ${makname}.wpb BINCOM $ROBASE
    
    # Extract Backtraces.axf for GCC compiler binaries
    if [ $Compiler == gcc ]
    then
        # Find AXFShrinker tool
        Test=$(uname)
        if [ "${Test/CYGWIN/}" == "$Test" ]
        then
            # Linux path
            AXKSPath=/projet/tools/share/Tatoo/AXFshrinker/V1.0.0.1
        else
            # Cygwin path
            AXKSPath=${SGT_DIR}/tools/cygwin
        fi
        
        # Extract backtrace file
        $AXKSPath/AXFshrinker out/${makname}.elf out/backtraces.axf
    fi
fi

# Displays error
find_err -sgt

# Get ZIP name
zipname=$(basename $(pwd)).zip

# Retrieve CoreSw backtrace file
if [ -f "$WMCOREHOME/$WMCORESW/backtraces64k.axf" ]; then cp -p "$WMCOREHOME/$WMCORESW/backtraces64k.axf" out/gen.backtraces64k.axf ; fi
if [ -f "$WMCOREHOME/$WMCORESW/out/tmt/backtraces64k.axf" ]; then cp -p "$WMCOREHOME/$WMCORESW/out/tmt/backtraces64k.axf" out/gen.backtraces64k.axf ; fi
chmod +w out/gen.backtraces64k.axf 2> /dev/null

# Retrieve CoreSw symbols file
if [ -f "$WMCOREHOME/$WMCORESW/s64k" ]; then cp -p "$WMCOREHOME/$WMCORESW/s64k" out/gen.s64k ; fi
if [ -f "$WMCOREHOME/$WMCORESW/out/tmt/symbolfiles/s64k" ]; then cp -p "$WMCOREHOME/$WMCORESW/out/tmt/symbolfiles/s64k" out/gen.s64k ; fi
chmod +w out/gen.s64k 2> /dev/null

# build backtraces and symbol files
if [ -f out/backtraces.axf ] && [ -f out/gen.backtraces64k.axf ]
then
    mv out/backtraces.axf out/backtraces.tmp
    cat out/gen.backtraces64k.axf out/backtraces.tmp > out/backtraces.axf
    
    # Update workspace
    cp out/backtraces.axf out/tmt
    (cd out/tmt ; zip $zipname backtraces.axf)
    
    # Clean up...
    rm -f out/backtraces.tmp out/gen.backtraces64k.axf
fi
if [ -f out/s ] && [ -f out/gen.s64k ]
then
    # Get Lines Nb
    linesNb=$(wc -l out/s | sed -e 's/[ ]*\([0-9]*\).*/\1/')
    
    # Remove EOF line
    head -n $(( linesNb )) out/s > out/s.tmp
    
    # Get Lines Nb
    linesNb=$(wc -l out/gen.s64k | sed -e 's/[ ]*\([0-9]*\).*/\1/')
    
    # Remove EOF line
    tail -n $(( linesNb - 2 )) out/gen.s64k > out/gen.s64k.tmp
    
    # Cat files
    cat out/s.tmp out/gen.s64k.tmp > out/s
    
    # Update workspace
    cp out/s out/tmt
    (cd out/tmt ; zip $zipname s)
    
    # Clean up...
    rm -f out/s.tmp out/gen.s64k out/gen.s64k.tmp
fi
